package com.xyz.study.redis.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * @author XYZ
 * @version 1.0.0
 * @since 2020-12-08 22:53
 */
@Configuration
public class RedisTemplateConfig {

    @Bean("manualRedisTemplate")
    public RedisTemplate<String, String> redisTemplate(@Qualifier("manualRedisConnectionFactory") RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean("manualRedisConnectionFactory")
    public RedisConnectionFactory redisConnectionFactory(){
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(8);
        genericObjectPoolConfig.setMinIdle(4);
        genericObjectPoolConfig.setMaxTotal(16);
        genericObjectPoolConfig.setMaxWaitMillis(60000);

        RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
        redisSentinelConfiguration.addSentinel(new RedisNode("192.168.110.14",26379));
        redisSentinelConfiguration.addSentinel(new RedisNode("192.168.110.15",26379));
        redisSentinelConfiguration.addSentinel(new RedisNode("192.168.110.16",26379));
        redisSentinelConfiguration.setMaster("mymaster");
        redisSentinelConfiguration.setSentinelPassword("123456");
        redisSentinelConfiguration.setDatabase(0);
        redisSentinelConfiguration.setPassword("123456");

        LettuceClientConfiguration lettuceClientConfiguration = LettucePoolingClientConfiguration.builder()
                .poolConfig(genericObjectPoolConfig).commandTimeout(Duration.ofSeconds(60)).build();
        return new LettuceConnectionFactory(redisSentinelConfiguration, lettuceClientConfiguration);
    }
}
